package com.javaweb.ser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;

import com.javaweb.utils.DB;

/**
 * Servlet implementation class Logins
 */
@WebServlet("/Logins.do")
public class Logins extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Logins() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
				String name=request.getParameter("username");
				String password=request.getParameter("password");
				System.out.println(name+"========="+password);
				List<Object> params=new ArrayList<>();
				params.add(name);
				Map<String, Object> map=new HashMap<>();
				DB.getCon();
				String sql="select * from jsp_users where userCount=?";
				try {
					map=DB.find(sql, params);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				DB.disConnect();
				System.out.println(map.get("userPassword"));
				if (!map.get("userPassword").equals(password)) {
					request.setAttribute("login","200");
					response.sendRedirect("/MidJavaWeb/Index/login.jsp");
				}else {
					request.getSession().setAttribute("login","400");
					request.getSession().setAttribute("username", map.get("username"));
					String des=Integer.parseInt(map.get("userLevel").toString())==0?"学生":"管理员";
					request.getSession().setAttribute("des", des);
					request.getSession().setAttribute("useracount", map.get("userCount"));
					//request.getRequestDispatcher("/Index/information.jsp").forward(request, response);
					response.sendRedirect("/MidJavaWeb/Index/information.jsp");
				}
	}

}
